const path = require('path');
const fs = require('fs').promises;
const chatService = require('../services/chatService');
const asrService = require('../services/asrService');
const logger = require('../utils/logger');
const chatMessageModel = require('../models/chatMessage');

/**
 * 获取聊天历史
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 */
exports.getChatHistory = async (req, res) => {
  try {
    const limit = parseInt(req.query.limit) || 20;
    const offset = parseInt(req.query.offset) || 0;
    
    const messages = await chatService.getChatHistory(limit, offset);
    
    res.json({
      success: true,
      data: messages,
      pagination: {
        limit,
        offset,
        total: messages.length // 注意：这不是真正的总数，只是当前返回的消息数
      }
    });
  } catch (error) {
    logger.error(`获取聊天历史失败: ${error.message}`);
    res.status(500).json({
      success: false,
      message: '获取聊天历史失败',
      error: error.message
    });
  }
};

/**
 * 发送文本消息
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 */
exports.sendTextMessage = async (req, res) => {
  try {
    const { content, sender = 'user' } = req.body;
    
    if (!content || content.trim() === '') {
      return res.status(400).json({
        success: false,
        message: '消息内容不能为空'
      });
    }
    
    // 创建消息对象
    const messageData = {
      type: 'text',
      content,
      sender
    };
    
    // 验证消息数据
    const validation = chatMessageModel.validate(messageData);
    if (!validation.isValid) {
      return res.status(400).json({
        success: false,
        message: '消息数据无效',
        errors: validation.errors
      });
    }
    
    // 保存消息
    const message = await chatService.sendMessage(messageData);
    
    // 广播消息给所有WebSocket客户端
    chatService.broadcastMessage({
      type: 'new_message',
      message
    });
    
    res.status(201).json({
      success: true,
      data: message
    });
  } catch (error) {
    logger.error(`发送文本消息失败: ${error.message}`);
    res.status(500).json({
      success: false,
      message: '发送文本消息失败',
      error: error.message
    });
  }
};

/**
 * 处理语音消息
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 */
exports.processVoiceMessage = async (req, res) => {
  try {
    // 检查是否有文件上传
    if (!req.file) {
      return res.status(400).json({
        success: false,
        message: '未上传音频文件'
      });
    }
    
    const audioFile = req.file;
    const filePath = audioFile.path;
    
    // 获取文件的相对路径（用于存储和访问）
    const relativePath = path.relative(path.join(__dirname, '..'), filePath).replace(/\\/g, '/');
    
    // 尝试识别语音内容
    let recognizedText = '';
    try {
      recognizedText = await asrService.recognizeSpeech(filePath);
      logger.info(`语音识别结果: "${recognizedText}"`);
    } catch (error) {
      logger.error(`语音识别失败: ${error.message}`);
      // 即使识别失败，我们仍然保存语音消息
    }
    
    // 创建语音消息
    const messageData = {
      type: 'voice',
      content: recognizedText, // 识别的文本作为内容
      sender: req.body.sender || 'user',
      fileInfo: {
        url: relativePath,
        name: audioFile.originalname,
        type: audioFile.mimetype,
        size: audioFile.size
      }
    };
    
    // 保存消息
    const message = await chatService.sendMessage(messageData);
    
    // 广播消息给所有WebSocket客户端
    chatService.broadcastMessage({
      type: 'new_message',
      message
    });
    
    res.status(201).json({
      success: true,
      data: message
    });
  } catch (error) {
    logger.error(`处理语音消息失败: ${error.message}`);
    res.status(500).json({
      success: false,
      message: '处理语音消息失败',
      error: error.message
    });
  }
};

/**
 * 删除消息
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 */
exports.deleteMessage = async (req, res) => {
  try {
    const messageId = req.params.id;
    
    if (!messageId) {
      return res.status(400).json({
        success: false,
        message: '消息ID不能为空'
      });
    }
    
    // 删除消息
    const success = await chatService.deleteMessage(messageId);
    
    if (!success) {
      return res.status(404).json({
        success: false,
        message: '未找到指定消息'
      });
    }
    
    // 广播删除消息事件
    chatService.broadcastMessage({
      type: 'system',
      action: 'delete_message',
      messageId
    });
    
    res.json({
      success: true,
      message: '消息已删除'
    });
  } catch (error) {
    logger.error(`删除消息失败: ${error.message}`);
    res.status(500).json({
      success: false,
      message: '删除消息失败',
      error: error.message
    });
  }
};

/**
 * 清空聊天历史
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 */
exports.clearChatHistory = async (req, res) => {
  try {
    // 清空聊天历史
    await chatService.clearChatHistory();
    
    // 广播清空历史事件
    chatService.broadcastMessage({
      type: 'system',
      action: 'clear_history'
    });
    
    res.json({
      success: true,
      message: '聊天历史已清空'
    });
  } catch (error) {
    logger.error(`清空聊天历史失败: ${error.message}`);
    res.status(500).json({
      success: false,
      message: '清空聊天历史失败',
      error: error.message
    });
  }
};

/**
 * 语音识别
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 */
exports.recognizeSpeech = async (req, res) => {
  try {
    // 检查是否有文件上传
    if (!req.file) {
      return res.status(400).json({
        success: false,
        message: '未上传音频文件'
      });
    }
    
    const audioFile = req.file;
    const filePath = audioFile.path;
    
    // 识别语音
    const recognizedText = await asrService.recognizeSpeech(filePath);
    
    // 识别完成后删除临时文件
    try {
      await fs.unlink(filePath);
      logger.debug(`临时音频文件已删除: ${filePath}`);
    } catch (unlinkError) {
      logger.warn(`删除临时音频文件失败: ${unlinkError.message}`);
      // 继续处理，不影响响应
    }
    
    res.json({
      success: true,
      data: {
        text: recognizedText
      }
    });
  } catch (error) {
    logger.error(`语音识别失败: ${error.message}`);
    res.status(500).json({
      success: false,
      message: '语音识别失败',
      error: error.message
    });
  }
};